package com.frame.work.frame.deal.device0fac;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import com.frame.work.common.constant.ZhiNengKongTiaoMianBanConstant;
import com.frame.work.common.util.JsonToMqtt;
import com.frame.work.config.RedisUtil;
import com.frame.work.config.SpringUtil;
import com.frame.work.entity.TemperatureControlLog;
import com.frame.work.frame.deal.base.BaseFrame;
import com.frame.work.service.TemperatureControlLogService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author zhanghui
 * @Date: 2021/07/05/16:15
 * @Description: 智能空调面板数据帧处理
 */
@Data
@Slf4j
public class ZhiNengKongTiaoMianBan_0FAC0502 extends BaseFrame {
    @JSONField(serialize = false)
    private List<String> deviceList;
    private String spreadingType;

    public ZhiNengKongTiaoMianBan_0FAC0502(String gatewayMac, String data) {
        super(gatewayMac, data);
        TemperatureControlLog temperatureControlLog = new TemperatureControlLog();
        temperatureControlLog.setGatewayMac(this.getGatewayMac());
        temperatureControlLog.setDeviceMac(this.getDeviceMac());
        deviceList = new ArrayList<>(3);
        this.spreadingType = getSpreadingTypeBydata(data);
        int firstBit = 0x01;
        // 温控使能标识，bit0空调使能、bit1地暖使能、bit2新风使能，其他bit无效；1使能，0失能
        String enableByte = StringUtils.substring(data, 48, 50);
        int enableInt = Integer.parseInt(enableByte, 16);
        String productType = this.getProductType();

        //当前温度
        String nowTemplate = getNowTemplate(data);
        //当前湿度
        String nowHumidity = getNowHumidity(data);
        temperatureControlLog.setIndoorTemperature(nowTemplate);
        temperatureControlLog.setIndoorHumidity(nowHumidity);
        Map<String, Object> airConditionActions = new HashMap<>(4);
        Map<String, Object> floorHeatingActions = new HashMap<>(2);
        Map<String, Object> freshAirActions = new HashMap<>(2);

        //若空调面板使能
        if ((enableInt & firstBit) == 1) {
            //空调面板模式（关闭状态下调模式，上报的属性依然为关闭；打开是上报状态没有"OPEN"，只有四个模式）
            String airConditionModeValue = StringUtils.substring(data, data.length() - 18, data.length() - 16);
            String airConditionModeName = ZhiNengKongTiaoMianBanConstant.AirConditionModeEnum.getNameByValue(airConditionModeValue);
            String airModeContent = ZhiNengKongTiaoMianBanConstant.AirConditionModeEnum.getContentByValue(airConditionModeValue);
            //空调面板风速
            String airConditionFanSpeedValue = StringUtils.substring(data, data.length() - 16, data.length() - 14);
            String airConditionFanSpeedName = ZhiNengKongTiaoMianBanConstant.AirConditionFanSpeedEnum.getNameByValue(airConditionFanSpeedValue);
            //空调面板温度
            String airConditionTemperature = StringUtils.substring(data, data.length() - 14, data.length() - 10);
            float airConditionTemperatureFloat = Float.parseFloat(StringUtils.substring(airConditionTemperature, 0, 2))
                    + Float.parseFloat(StringUtils.substring(airConditionTemperature, 2, 4)) / 100;

            if ("CLOSE".equals(airConditionModeName)) {
                airConditionActions.put("switchState", "02");
            } else {
                airConditionActions.put("switchState", "01");
            }
            airConditionActions.put("mode", airConditionModeName);
            airConditionActions.put("fanSpeed", airConditionFanSpeedName);
            airConditionActions.put("temperature", airConditionTemperatureFloat + "");
            airConditionActions.put("nowTemplate", nowTemplate);
            airConditionActions.put("nowHumidity", nowHumidity);
            temperatureControlLog.setAcContent(JSONObject.toJSONString(airConditionActions));
            this.setActions(airConditionActions);
            this.setProductType(productType + "_1");
            String objectJsonStr = JSONObject.toJSONString(this);
            JsonToMqtt.sendMQTT(gatewayMac, objectJsonStr);
            deviceList.add(objectJsonStr);
        }

        //若地暖面板使能
        if (((enableInt >> 1) & firstBit) == 1) {
            //地暖模式
            String floorHeatingModeValue = StringUtils.substring(data, data.length() - 10, data.length() - 8);
            String floorHeatingModeName = "01".equals(floorHeatingModeValue) ? "OPEN" : "CLOSE";
            //地暖温度
            String floorHeatingTemperatureValue = StringUtils.substring(data, data.length() - 8, data.length() - 4);
            float floorHeatingTemperatureFloat = Float.parseFloat(floorHeatingTemperatureValue.substring(0, 2))
                    + Float.parseFloat(floorHeatingTemperatureValue.substring(2, 4)) / 100;

            if ("OPEN".equals(floorHeatingModeName)) {
                floorHeatingActions.put("switchState", "01");
            } else {
                floorHeatingActions.put("switchState", "02");
            }
            floorHeatingActions.put("temperature", floorHeatingTemperatureFloat + "");
            floorHeatingActions.put("nowTemplate", nowTemplate);
            floorHeatingActions.put("nowHumidity", nowHumidity);
            temperatureControlLog.setFloorHeatContent(JSONObject.toJSONString(floorHeatingActions));
            this.setActions(floorHeatingActions);
            this.setProductType(productType + "_2");
            String objectJsonStr = JSONObject.toJSONString(this);
            JsonToMqtt.sendMQTT(gatewayMac, objectJsonStr);
            deviceList.add(objectJsonStr);
        }

        //若新风面板使能
        if (((enableInt >> 2) & firstBit) == 1) {
            //新风模式
            String freshAirModeValue = StringUtils.substring(data, data.length() - 4, data.length() - 2);
            String freshAirModeName = "01".equals(freshAirModeValue) ? "OPEN" : "CLOSE";
            String freshAirFanSpeedValue = StringUtils.substring(data, data.length() - 2, data.length());
            String freshAirFanSpeedName = ZhiNengKongTiaoMianBanConstant.FreshAirFanSpeed.getNameByValue(freshAirFanSpeedValue);
            if ("OPEN".equals(freshAirModeName)) {
                freshAirActions.put("switchState", "01");
            } else {
                freshAirActions.put("switchState", "02");
            }
            freshAirActions.put("fanSpeed", freshAirFanSpeedName);
            freshAirActions.put("nowTemplate", nowTemplate);
            freshAirActions.put("nowHumidity", nowHumidity);
            temperatureControlLog.setFreshAirContent(JSONObject.toJSONString(freshAirActions));
            this.setActions(freshAirActions);
            this.setProductType(productType + "_3");
            String objectJsonStr = JSONObject.toJSONString(this);
            JsonToMqtt.sendMQTT(gatewayMac, objectJsonStr);
            deviceList.add(objectJsonStr);
        }
        saveLog(temperatureControlLog);
    }

    private String getSpreadingTypeBydata(String data) {
        return StringUtils.substring(data, 38, 40);
    }

    public static void dealFrame(String gatewayMac, String data) {
        ZhiNengKongTiaoMianBan_0FAC0502 zhiNengKongTiaoMianBan = new ZhiNengKongTiaoMianBan_0FAC0502(gatewayMac, data);
        RedisTemplate redisTemplate = RedisUtil.getRedisTemplate();

        // 若是主动上报，将设备的数据存入redis，保存5分钟
        if ("00".equals(zhiNengKongTiaoMianBan.getDataType())) {
            if (zhiNengKongTiaoMianBan.deviceList.size() > 0) {
                String key = gatewayMac + "_" + zhiNengKongTiaoMianBan.getDeviceMac();
                redisTemplate.opsForValue().set(key, JSONObject.toJSONString(zhiNengKongTiaoMianBan.deviceList), 1, TimeUnit.MINUTES);
            }
        }
    }

    /**
     * 获取当前温度
     *
     * @param data
     * @return
     */
    private String getNowTemplate(String data) {
        String nowTemplate = StringUtils.substring(data, 58, 62);
        String start = StringUtils.substring(nowTemplate, 0, 2);
        String end = StringUtils.substring(nowTemplate, 2, 3);
        return start + "." + end;
    }

    /**
     * 获取当前湿度
     *
     * @param data
     * @return
     */
    private String getNowHumidity(String data) {
        String nowHumidity = StringUtils.substring(data, 62, 66);
        String start = StringUtils.substring(nowHumidity, 0, 2);
        String end = StringUtils.substring(nowHumidity, 2, 3);
        return start + "." + end;
    }

    /**
     * 保存日志信息
     *
     * @param temperatureControlLog
     */
    private void saveLog(TemperatureControlLog temperatureControlLog) {
        try {
            TemperatureControlLogService temperatureControlLogService = SpringUtil.getBean(TemperatureControlLogService.class);
            boolean save = temperatureControlLogService.save(temperatureControlLog);
            if (!save) {
                log.warn("保存日志失败");
            }
        } catch (Exception e) {
            log.warn("保存日志失败：{}", e.getMessage());
        }
    }


}
